package com.xunwulian.web.interceptor;

import com.xunwulian.base.entity.Menu;
import com.xunwulian.base.entity.User;
import com.xunwulian.web.util.Const;
import com.xunwulian.web.util.JurisdictionHelper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

public class LoginHandlerInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws
            Exception {
        // TODO Auto-generated method stub
        String path = request.getServletPath();
        String contextPath = request.getContextPath();
        if (path == null || "".equals(path) || path.matches(Const.NO_INTERCEPTOR_PATH) || ("".equals(contextPath) && "/".equals(path))) {
            System.out.println("don't need auth path:" + path);
            return true;
        } else {
            //shiro管理的session
            Subject currentUser = SecurityUtils.getSubject();
            Session session = currentUser.getSession();
            User user = (User) session.getAttribute(Const.SESSION_USER);

            if (user != null) {
                path = path.substring(1, path.length());

                List<Menu> menuList = (List) session.getAttribute(Const.SESSION_allmenuList); //获取菜单列表

                Map<String, String> mapQX = (Map<String, String>) session.getAttribute(Const.SESSION_QX);//按钮权限
                mapQX.remove("add");
                mapQX.remove("del");
                mapQX.remove("edit");
                mapQX.remove("cha");
                String userName = session.getAttribute(Const.SESSION_USERNAME).toString();    //获取当前登录者loginname
                boolean b = JurisdictionHelper.hasJurisdiction(path, userName, menuList, mapQX);

                session.removeAttribute(Const.SESSION_QX);
                session.setAttribute(Const.SESSION_QX, mapQX);    //重新分配按钮权限

                if (!b) {
                    response.sendRedirect(request.getContextPath() + Const.LOGIN);
                }
                return b;

            } else {
                //登陆过滤
                response.sendRedirect(request.getContextPath() + Const.LOGIN);
                System.out.println("user is null, Const.Login:" + request.getContextPath() + Const.LOGIN + ", "
                        + request.getServletPath());
                return false;
                //                return true;
            }
        }
    }

}
